<template>
  <view class="container">
    <view class="page-header">
      <view class="back-btn" @click="goBack">
        <text class="back-icon">&lt;</text>
        <text class="back-text">返回</text>
      </view>
      <view class="page-title">编辑资料</view>
    </view>
    
    <view class="profile-form">
      <!-- 头像上传区域 -->
      <view class="avatar-section">
        <view class="avatar-wrapper" @click="chooseAvatar">
          <image class="avatar-image" :src="fullAvatarUrl" mode="aspectFill"></image>
          <view class="avatar-edit-icon">
            <uni-icons type="camera-filled" size="20" color="#FFFFFF"></uni-icons>
          </view>
        </view>
        <text class="avatar-tip">点击更换头像</text>
      </view>
      
      <view class="form-group">
        <text class="form-label">用户名</text>
        <input class="form-input" type="text" v-model="profileData.username" placeholder="请输入用户名" />
      </view>
      
      <view class="form-group">
        <text class="form-label">姓名</text>
        <input class="form-input" type="text" v-model="profileData.name" placeholder="请输入姓名" />
      </view>
      
      <view class="form-group">
        <text class="form-label">手机号码</text>
        <input class="form-input" type="number" v-model="profileData.phone" placeholder="请输入手机号码" maxlength="11" />
      </view>
      
      <view class="form-group">
        <text class="form-label">电子邮箱</text>
        <input class="form-input" type="text" v-model="profileData.email" placeholder="请输入电子邮箱" />
      </view>
      
      <view class="form-group">
        <text class="form-label">性别</text>
        <picker class="form-picker" @change="bindGenderChange" :value="genderIndex" :range="genders">
          <view class="picker-value">
            {{ profileData.gender ? (profileData.gender === 'M' ? '男' : '女') : '请选择性别' }}
          </view>
        </picker>
      </view>
      
      <button class="btn-save" @click="saveProfile">保存</button>
    </view>
  </view>
</template>

<script>
import { getUserProfile, updateUserProfile } from '@/api/auth.js'

export default {
  data() {
    return {
      profileData: {
        username: '',
        name: '',
        phone: '',
        email: '',
        gender: '',
        avatar_url: ''
      },
      genders: ['男', '女'],
      genderIndex: 0,
      tempFilePath: '', // 临时头像路径
      baseUrl: '' // 基础URL
    }
  },
  
  computed: {
    fullAvatarUrl() {
      const avatar = this.profileData?.avatar_url
      
      // 如果没有头像，返回默认头像
      if (!avatar) {
        return '/static/images/avatar-default.png'
      }
      
      // 如果是预设头像（以/assets/开头），直接返回
      if (avatar.startsWith('/assets/')) {
        return avatar
      }
      
      // 如果是服务器上的媒体文件（以media/开头）
      if (avatar.startsWith('media/')) {
        return this.baseUrl + '/' + avatar
      }
      
      // 如果已经是完整URL（包含http或https）
      if (avatar.startsWith('http://') || avatar.startsWith('https://')) {
        return avatar
      }
      
      // 如果是从服务器返回的相对路径
      if (avatar.includes('media/avatars/')) {
        return this.baseUrl + '/' + avatar
      }
      
      // 如果是本地临时文件路径（微信小程序格式）
      if (avatar.startsWith('wxfile://') || avatar.startsWith('http://tmp/') || 
          avatar.startsWith('file://') || avatar.startsWith('/storage/')) {
        return avatar
      }
      
      // 默认情况，拼接baseUrl
      return this.baseUrl + avatar
    }
  },
  
  onLoad() {
    // 获取当前环境下的baseUrl
    this.baseUrl = getApp().globalData.baseUrl || ''
    this.fetchUserProfile()
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack()
    },
    
    // 获取用户个人资料
    async fetchUserProfile() {
      try {
        uni.showLoading({ title: '加载中...' })
        
        const res = await getUserProfile()
        
        if (res.code === 200 && res.data) {
          const data = res.data
          this.profileData = {
            username: data.username || '',
            name: data.name || '',
            phone: data.phone || '',
            email: data.email || '',
            gender: data.gender || '',
            avatar_url: data.avatar_url || ''
          }
          
          // 设置性别选择器索引
          this.genderIndex = this.profileData.gender === 'M' ? 0 : 1
        } else {
          uni.showToast({
            title: '获取个人资料失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('获取个人资料失败:', error)
        uni.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    },
    
    // 选择头像图片
    chooseAvatar() {
      uni.chooseImage({
        count: 1, // 只能选一张图片
        sizeType: ['compressed'], // 压缩图片
        sourceType: ['album', 'camera'], // 可以从相册或相机选择
        success: (res) => {
          this.tempFilePath = res.tempFilePaths[0]
          
          // 上传头像到服务器
          this.uploadAvatarToServer(this.tempFilePath)
        },
        fail: (err) => {
          console.error('选择图片失败:', err)
        }
      })
    },
    
    // 上传头像到服务器
    uploadAvatarToServer(filePath) {
      // 显示上传中的提示
      uni.showLoading({
        title: '上传中...'
      })
      
      // 获取BASE_URL
      const BASE_URL = this.baseUrl // 使用data中的baseUrl
      
      // 使用uni.uploadFile上传文件到后端
      uni.uploadFile({
        url: BASE_URL + '/api/users/avatar/update/',
        filePath: filePath,
        name: 'avatar',
        header: {
          'Authorization': uni.getStorageSync('token') ? `Bearer ${uni.getStorageSync('token')}` : ''
        },
        success: (uploadRes) => {
          console.log('上传头像响应:', uploadRes)
          
          // 检查响应状态码
          if (uploadRes.statusCode !== 200) {
            uni.showToast({
              title: `服务器返回错误: ${uploadRes.statusCode}`,
              icon: 'none'
            })
            return
          }
          
          let result
          // 解析JSON响应
          try {
            result = JSON.parse(uploadRes.data)
            console.log('解析后的响应数据:', result)
          } catch (e) {
            console.error('解析响应失败:', e, '原始响应:', uploadRes.data)
            uni.showToast({
              title: '响应格式错误',
              icon: 'none'
            })
            return
          }
          
          // 处理成功响应
          if (result.code === 200 && result.avatar_url) {
            // 更新本地头像URL
            this.profileData.avatar_url = result.avatar_url
            
            uni.showToast({
              title: '头像上传成功',
              icon: 'success'
            })
            
            // 更新本地缓存的用户头像
            const userInfo = uni.getStorageSync('userInfo')
            if (userInfo) {
              userInfo.avatarUrl = result.avatar_url
              uni.setStorageSync('userInfo', userInfo)
            }
          } else {
            uni.showToast({
              title: result.message || '头像上传失败',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          console.error('上传头像失败:', err)
          uni.showToast({
            title: '头像上传失败: ' + (err.errMsg || JSON.stringify(err)),
            icon: 'none'
          })
        },
        complete: () => {
          uni.hideLoading()
        }
      })
    },
    
    // 性别选择器变化
    bindGenderChange(e) {
      this.genderIndex = e.detail.value
      this.profileData.gender = this.genderIndex === 0 ? 'M' : 'F'
    },
    
    // 保存个人资料
    async saveProfile() {
      try {
        uni.showLoading({ title: '保存中...' })
        
        const res = await updateUserProfile(this.profileData)
        
        if (res.code === 200) {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          })
          
          // 更新本地缓存的用户信息
          const userInfo = uni.getStorageSync('userInfo') || {}
          userInfo.username = this.profileData.username
          userInfo.name = this.profileData.name
          userInfo.phone = this.profileData.phone
          userInfo.email = this.profileData.email
          uni.setStorageSync('userInfo', userInfo)
          
          // 延迟返回上一页
          setTimeout(() => {
            uni.navigateBack()
          }, 1500)
        } else {
          uni.showToast({
            title: res.message || '保存失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('保存个人资料失败:', error)
        uni.showToast({
          title: '网络错误，请稍后再试',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 30rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 40rpx;
  position: relative;
}

.back-btn {
  display: flex;
  align-items: center;
  position: absolute;
  left: 0;
}

.back-icon {
  font-size: 36rpx;
  color: #007AFF;
}

.back-text {
  font-size: 28rpx;
  color: #007AFF;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  flex: 1;
  text-align: center;
}

.profile-form {
  background-color: #ffffff;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0 40rpx;
}

.avatar-wrapper {
  position: relative;
  width: 160rpx;
  height: 160rpx;
  border-radius: 80rpx;
  overflow: hidden;
  margin-bottom: 16rpx;
  background-color: #f0f0f0;
}

.avatar-image {
  width: 100%;
  height: 100%;
}

.avatar-edit-icon {
  position: absolute;
  right: 0;
  bottom: 0;
  width: 50rpx;
  height: 50rpx;
  background-color: rgba(0, 122, 255, 0.8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-tip {
  font-size: 24rpx;
  color: #999;
}

.form-group {
  margin-bottom: 30rpx;
}

.form-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.form-input, .form-picker {
  width: 100%;
  height: 80rpx;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  background-color: #f8f8f8;
}

.picker-value {
  height: 80rpx;
  line-height: 80rpx;
}

.btn-save {
  background-color: #007AFF;
  color: #ffffff;
  margin-top: 40rpx;
  height: 90rpx;
  line-height: 90rpx;
  font-size: 32rpx;
  border-radius: 45rpx;
}
</style> 